// pages/rankings/rankings.js
const app = getApp();

Page({
  data: {
    activeTab: 'total_score', // total_score, win_rate, total_games
    periodOptions: ['全部', '本周', '本月'],
    selectedPeriodIndex: 0,
    rankings: [],
    topRankings: [],
    myRank: {
      nickname: '',
      avatar: '',
      rank: 0,
      score: 0,
      rank_desc: ''
    },
    myStats: {
      total_games: 0,
      win_count: 0,
      lose_count: 0,
      win_rate: 0,
      total_score: 0,
      avg_score: 0
    },
    loading: false
  },
  
  onLoad: function() {
    // 加载排名数据
    this.loadRankings();
  },
  
  // 切换Tab
  switchTab: function(e) {
    const tab = e.currentTarget.dataset.tab;
    
    this.setData({ activeTab: tab });
    
    // 重新加载排名数据
    this.loadRankings();
  },
  
  // 改变统计周期
  changePeriod: function(e) {
    this.setData({ 
      selectedPeriodIndex: e.detail.value 
    });
    
    // 重新加载排名数据
    this.loadRankings();
  },
  
  // 加载排名数据
  loadRankings: function() {
    const that = this;
    
    this.setData({ loading: true });
    
    wx.showLoading({ title: '加载中...' });
    
    // 获取统计周期
    const period = this.data.selectedPeriodIndex === 0 ? 'all' : 
                   this.data.selectedPeriodIndex === 1 ? 'week' : 'month';
    
    app.request('/user/rankings', {
      params: {
        type: this.data.activeTab,
        period: period
      }
    }).then(res => {
      wx.hideLoading();
      
      // 处理排名数据
      const formattedRankings = res.rankings.map(ranking => ({
        id: ranking.id,
        nickname: ranking.nickname,
        avatar: ranking.avatar,
        score: that.formatScore(ranking.score),
        rank_desc: that.getRankDesc(ranking)
      }));
      
      // 将前三名与其他排名分开
      const topRankings = formattedRankings.slice(0, 3);
      
      // 找到当前用户的排名
      const myInfo = res.rankings.find(r => r.id === app.globalData.userInfo.id) || 
                    { nickname: app.globalData.userInfo.nickname,
                      avatar: app.globalData.userInfo.avatar,
                      rank: 0,
                      score: 0,
                      win_count: 0,
                      lose_count: 0,
                      total_score: 0,
                      total_games: 0 };
      
      this.setData({
        rankings: formattedRankings,
        topRankings: topRankings,
        myRank: {
          nickname: myInfo.nickname,
          avatar: myInfo.avatar,
          rank: myInfo.rank || '--',
          score: this.formatScore(myInfo.score || 0),
          rank_desc: this.getRankDesc(myInfo)
        },
        myStats: {
          total_games: myInfo.total_games || 0,
          win_count: myInfo.win_count || 0,
          lose_count: myInfo.lose_count || 0,
          win_rate: myInfo.win_count && myInfo.total_games ? 
                   Math.round((myInfo.win_count / myInfo.total_games) * 100) : 0,
          total_score: myInfo.total_score || 0,
          avg_score: myInfo.total_games ? 
                    Math.round(myInfo.total_score / myInfo.total_games) : 0
        },
        loading: false
      });
      
      wx.hideLoading();
    }).catch(() => {
      this.setData({ loading: false });
      wx.hideLoading();
      wx.showToast({
        title: '加载失败，请重试',
        icon: 'none'
      });
    });
  },
  
  // 格式化分数显示
  formatScore: function(score) {
    if (this.data.activeTab === 'total_score') {
      // 积分格式化为整数
      return Math.round(score);
    } else if (this.data.activeTab === 'win_rate') {
      // 胜率格式化为百分比
      return Math.round(score) + '%';
    }
    return score;
  },
  
  // 获取排名描述
  getRankDesc: function(ranking) {
    if (this.data.activeTab === 'total_score') {
      return `${ranking.total_games || 0}局游戏`;
    } else if (this.data.activeTab === 'win_rate') {
      return `${ranking.win_count || 0}胜${ranking.lose_count || 0}负`;
    } else {
      return `${Math.round((ranking.win_count / ranking.total_games) * 100) || 0}%胜率`;
    }
  },
  
  // 返回上一页
  navigateBack: function() {
    wx.navigateBack();
  },
  
  /**
   * 头像加载失败处理
   */
  onAvatarError: function (e) {
    const { dataset } = e.currentTarget;
    // 当头像加载失败时，设置为默认头像
    // 如果有dataset信息，可以针对性地更新对应的头像
    console.log('头像加载失败，使用默认头像');
  }
});